import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class RegisterController extends GetxController {
  RegisterController();

  // 存储库
  final UserRepository _userRepository = UserRepository();

  // 表单控制器
  final TextEditingController usernameController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  final TextEditingController confirmPasswordController =
      TextEditingController();

  // 焦点控制器
  final FocusNode usernameFocusNode = FocusNode();
  final FocusNode passwordFocusNode = FocusNode();
  final FocusNode confirmPasswordFocusNode = FocusNode();

  // 表单状态
  final RxBool obscurePassword = true.obs;
  final RxBool obscureConfirmPassword = true.obs;

  // 表单全局key
  final formKey = GlobalKey<FormState>();

  // 切换密码显示
  void togglePasswordVisibility() {
    obscurePassword.value = !obscurePassword.value;
  }

  // 切换确认密码显示
  void toggleConfirmPasswordVisibility() {
    obscureConfirmPassword.value = !obscureConfirmPassword.value;
  }

  // 执行注册
  void register() async {
    // 检查输入是否完整
    if (usernameController.text.isEmpty) {
      EasyLoading.showError('Username is required');
      return;
    }

    if (passwordController.text.isEmpty) {
      EasyLoading.showError('Password is required');
      return;
    }

    if (confirmPasswordController.text.isEmpty) {
      EasyLoading.showError('Please confirm your password');
      return;
    }

    // 检查两次密码是否一致
    if (passwordController.text != confirmPasswordController.text) {
      EasyLoading.showError('Passwords do not match');
      return;
    }

    EasyLoading.show(status: 'Registering...');

    try {
      // 调用存储库注册方法
      final user = await _userRepository.register(
        username: usernameController.text.trim(),
        password: passwordController.text,
      );

      if (user == null) {
        EasyLoading.dismiss();
        EasyLoading.showError('Username already exists');
        return;
      }

      // 注册成功，关闭加载提示
      EasyLoading.dismiss();

      // 显示注册成功提示
      EasyLoading.showSuccess('Registration successful');

      // 等待一段时间后返回登录页面
      await Future.delayed(const Duration(seconds: 1));

      // 返回登录页面（而不是直接进入主页）
      Get.back();
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError('Registration failed: ${e.toString()}');
    }
  }

  // 返回登录页面
  void goToLogin() {
    Get.back();
  }



  @override
  void onClose() {
    usernameController.dispose();
    passwordController.dispose();
    confirmPasswordController.dispose();
    usernameFocusNode.dispose();
    passwordFocusNode.dispose();
    confirmPasswordFocusNode.dispose();
    super.onClose();
  }
}
